package apple.encryptedNote.activities;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Date;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
import apple.encryptedNode.R;
import apple.encryptedNode.dao.EncryptedNodeOpenHelper;
import apple.encryptedNode.dao.OperationDAO;
import apple.encryptedNote.tools.EncryptTool;

public class EncryptedNoteActivity extends ListActivity {
	private Cursor mCursor;
	private OperationDAO operationDAO;
	private Long firstClickTime;
	private int longSelectPosition = -1;

	// private Button newNoteButton;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		operationDAO = new OperationDAO(this);
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.main);
		setContentView(R.layout.mainview);

		/*
		 * ArrayList<HashMap<String,String>> list = new
		 * ArrayList<HashMap<String,String>>(); HashMap<String, String> map1 =
		 * new HashMap<String, String>(); map1.put("textView1", "sdfsdfsdf");
		 * HashMap<String, String> map2 = new HashMap<String, String>();
		 * map2.put("textView1", "appleappleapple"); list.add(map1);
		 * list.add(map2);
		 * 
		 * SimpleAdapter listAdapter = new
		 * SimpleAdapter(this,list,R.layout.note_list_component, new
		 * String[]{"textView1"}, new int[]{R.id.topicName});
		 * setListAdapter(listAdapter);
		 */

		// mCursor = this.getContentResolver().query(People.CONTENT_URI, null,
		// null, null, null);
		firstClickTime = 0l;
		mCursor = this.operationDAO.query();
		startManagingCursor(mCursor);
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
		// android.R.layout.two_line_list_item,
				R.layout.note_list_component, mCursor,
				// new String[] {People.NAME},
				new String[] { EncryptedNodeOpenHelper.KEY_NAME, EncryptedNodeOpenHelper.KEY_CONTENT }, new int[] {
						R.id.topicName, R.id.topicContent });
 
		setListAdapter(adapter);
		// getListView().;
//		ImageView image = (ImageView) getListView().getAdapter().getView(0, null, getListView()).findViewById(
//				R.id.encryptionStatus);
//		image.setImageResource(R.drawable.notepad);
//		
//		TextView textView = (TextView) getListView().getAdapter().getView(0, null, getListView()).findViewById(
//				R.id.topicName);
//		textView.setText("adamadamadam");
		//setListAdapter(adapter);
//		adapter.notifyDataSetChanged();
		//adapter.
		//((SimpleAdapter) adapter).notifyViewChanaged();
		//getListView().draw(this.getc);
		// image.refreshDrawableState();
//		Log.e("adam", "textView.getText: " + textView.getText());
//		Log.e("adam", ""
//				+ getListView().getAdapter().getView(1, null, getListView()).findViewById(R.id.noteListComponentIcon));
//		Log.e("adam", "listViewChildren: "
//				+ (getListView().getAdapter().getView(1, null, getListView()).findViewById(R.id.encryptionStatus)));
		// ImageView image =
		// ((ImageView)(getListView().getChildAt(0).findViewById(R.id.encryptionStatus)));
		// image.setImageResource(R.drawable.notepad);
		// ListView listView = new ListView(this);

		// newNoteButton = (Button) findViewById(R.id.newNoteButton);
		/*
		 * newNoteButton.setOnClickListener(new OnClickListener() {
		 * 
		 * @Override public void onClick(View arg0) { Intent
		 * newNoteActivityIntent = new Intent();
		 * newNoteActivityIntent.setClass(EncryptedNoteActivity.this,
		 * NewNoteActivity.class);
		 * EncryptedNoteActivity.this.startActivity(newNoteActivityIntent); }
		 * });
		 */
		getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				longSelectPosition = arg2;//��2������ǳ�����item.
				final CharSequence[] items = { getString(R.string.open), getString(R.string.delete),
						getString(R.string.encrypt), getString(R.string.decrypt) };
				AlertDialog.Builder builder = new AlertDialog.Builder(EncryptedNoteActivity.this);
				builder.setTitle("Operations");
				builder.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						switch (item) {
						case 0:// open
							if (longSelectPosition > -1) {
								mCursor.moveToPosition(longSelectPosition);
								int keyId = mCursor.getInt(0);
								String keyName = mCursor.getString(1);
								String keyContent = mCursor.getString(2);
								longSelectPosition = -1;
								showNewNoteActivity(keyId, keyName, keyContent);
							}
							break;
						case 1:// delete
							if (longSelectPosition > -1) {
								mCursor.moveToPosition(longSelectPosition);
								int id = mCursor.getInt(0);
								String fileName = mCursor.getString(1);
								if (fileName.contains(" *encrypted*")) {
									Log.e("adam", "Contains encrypted");
									AlertDialog.Builder builder = new AlertDialog.Builder(EncryptedNoteActivity.this);
									builder.setMessage("Please decrypt this note first!").setCancelable(false)
											.setNegativeButton("Comfirm", new DialogInterface.OnClickListener() {
												public void onClick(DialogInterface dialog, int id) {
													dialog.cancel();
												}
											});
									AlertDialog alert = builder.create();
									alert.show();
								} else {
									longSelectPosition = -1;
									operationDAO.delete(id);
									// mCursor = operationDAO.query();
									mCursor.requery();
									startManagingCursor(mCursor);
									EncryptedNoteActivity.this.getListView().clearDisappearingChildren();
								}
							}

							break;
						case 2:// encrypt
							mCursor.moveToPosition(longSelectPosition);
							//int id = mCursor.getInt(0);
							String fileName = mCursor.getString(1);
							if (fileName.contains(" *encrypted*")) {
								Log.e("adam", "Contains encrypted");
								AlertDialog.Builder builder = new AlertDialog.Builder(EncryptedNoteActivity.this);
								builder.setMessage("This note is already encrypted!").setCancelable(false)
										.setNegativeButton("Comfirm", new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog, int id) {
												dialog.cancel();
											}
										});
								AlertDialog alert = builder.create();
								alert.show();
							} else {
								Dialog encryptionDialog = new Dialog(EncryptedNoteActivity.this);
								encryptionDialog.setContentView(R.layout.encryptiondialog);
								encryptionDialog.setTitle("Type your password!");
								Button dialogOperateButton = (Button) encryptionDialog
										.findViewById(R.id.dialogOperateButton);
								dialogOperateButton.setText("Encrypt");
								Button dialogCancelButton = (Button) encryptionDialog
										.findViewById(R.id.dialogCancelButton);
								dialogCancelButton.setOnClickListener(new DialogDismiss(encryptionDialog));
								dialogOperateButton.setOnClickListener(new DialogEncryptionBtnEvent(encryptionDialog));

								encryptionDialog.show();
							}
							break;
						case 3:// decrypt
							mCursor.moveToPosition(longSelectPosition);
							//int id1 = mCursor.getInt(0);
							String fileName1 = mCursor.getString(1);
							Log.e("adam", "fileName:" + fileName1 + fileName1.contains(" *encrypted*"));
							if (!fileName1.contains(" *encrypted*")) {
								Log.e("adam", "not Contains encrypted");
								AlertDialog.Builder builder = new AlertDialog.Builder(EncryptedNoteActivity.this);
								builder.setMessage("This note is not encrypted!").setCancelable(false)
										.setNegativeButton("Comfirm", new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog, int id) {
												dialog.cancel();
											}
										});
								AlertDialog alert = builder.create();
								alert.show();
							} else {
								Dialog decryptionDialog = new Dialog(EncryptedNoteActivity.this);
								decryptionDialog.setContentView(R.layout.encryptiondialog);
								decryptionDialog.setTitle("Type your password!");
								Button dialogOperateButtonForDe = (Button) decryptionDialog
										.findViewById(R.id.dialogOperateButton);
								dialogOperateButtonForDe.setText("Decrypt");
								Button dialogCancelButtonForDe = (Button) decryptionDialog
										.findViewById(R.id.dialogCancelButton);
								dialogCancelButtonForDe.setOnClickListener(new DialogDismiss(decryptionDialog));
								dialogOperateButtonForDe.setOnClickListener(new DialogDecryptionBtnEvent(
										decryptionDialog));

								decryptionDialog.show();
							}
							break;

						}

					}
				});
				AlertDialog alert = builder.create();
				alert.show();
				return true;
			}

		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.encryptednoteactivitymenu, menu);
		return true;

	}

	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_open:
			// EncryptedNoteActivity.this.
			int position = EncryptedNoteActivity.this.getSelectedItemPosition();
			Log.e("adam", "position: " + position);
			Toast.makeText(EncryptedNoteActivity.this, "position: " + position, Toast.LENGTH_SHORT).show();
			if (position > -1) {
				mCursor.moveToPosition(position);
				int keyId = mCursor.getInt(0);
				String keyName = mCursor.getString(1);
				String keyContent = mCursor.getString(2);
				showNewNoteActivity(keyId, keyName, keyContent);
			}
			Toast.makeText(EncryptedNoteActivity.this, "menu_open", Toast.LENGTH_SHORT).show();
			return true;
		case R.id.menu_new:
			showNewNoteActivity(-1, null, null);
			return true;
		case R.id.menu_delete:
			Toast.makeText(EncryptedNoteActivity.this, "menu_delete", Toast.LENGTH_SHORT).show();
			return true;
		case R.id.menu_config:
			Toast.makeText(EncryptedNoteActivity.this, "menu_config", Toast.LENGTH_SHORT).show();
			return true;
		case R.id.menu_about:
			Toast.makeText(EncryptedNoteActivity.this, "menu_about", Toast.LENGTH_SHORT).show();
			return true;
		case R.id.menu_exit:
			Toast.makeText(EncryptedNoteActivity.this, "menu_exit", Toast.LENGTH_SHORT).show();
			EncryptedNoteActivity.this.finish();
			return true;
		}
		return false;
	}

	// it will fired when we click one record in listView.
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Log.e("Adam", "itemClick");
		Long currentClickTime = new Date().getTime();
		// act as a double click and then show the NewNoteActivity.
		if (currentClickTime - firstClickTime < 1100) {
			currentClickTime = new Long(0);
			mCursor.moveToPosition(position);
			int keyId = mCursor.getInt(0);
			String keyName = mCursor.getString(1);
			String keyContent = mCursor.getString(2);
			showNewNoteActivity(keyId, keyName, keyContent);
			Toast.makeText(EncryptedNoteActivity.this, "doubleClick", Toast.LENGTH_SHORT).show();

		} else {
			/*
			 * ListView lv = null; lv.getch
			 */
			// l.setSelection(position);
			l.setSelected(true);

			// l.setSelector(position);
			// l.getChildAt(position).setSelected(true);

		}
		firstClickTime = currentClickTime;

	}

	@Override
	public boolean onKeyLongPress(int keyCode, KeyEvent event) {
		Toast.makeText(EncryptedNoteActivity.this, "keyPressed: " + event.describeContents(), Toast.LENGTH_SHORT)
				.show();
		return super.onKeyLongPress(keyCode, event);
	}

	public void showNewNoteActivity(int keyId, String keyName, String keyContent) {
		Intent newNoteActivityIntent = new Intent();
		if (keyName != null || keyContent != null) {
			newNoteActivityIntent.putExtra("keyId", keyId);
			newNoteActivityIntent.putExtra("keyName", keyName);
			newNoteActivityIntent.putExtra("keyContent", keyContent);
		}
		newNoteActivityIntent.setClass(EncryptedNoteActivity.this, NewNoteActivity.class);
		EncryptedNoteActivity.this.startActivity(newNoteActivityIntent);
	}

	@Override
	protected void onResume() {

		mCursor = this.operationDAO.query();
		startManagingCursor(mCursor);
		ListAdapter adapter = new SimpleCursorAdapter(this,
		// android.R.layout.two_line_list_item,
				R.layout.note_list_component, mCursor,
				// new String[] {People.NAME},
				new String[] { EncryptedNodeOpenHelper.KEY_NAME, EncryptedNodeOpenHelper.KEY_CONTENT }, new int[] {
						R.id.topicName, R.id.topicContent });
		setListAdapter(adapter);

		super.onResume();
	}

	@Override
	protected void onPause() {
		mCursor = this.operationDAO.query();
		startManagingCursor(mCursor);
		ListAdapter adapter = new SimpleCursorAdapter(this,
		// android.R.layout.two_line_list_item,
				R.layout.note_list_component, mCursor,
				// new String[] {People.NAME},
				new String[] { EncryptedNodeOpenHelper.KEY_NAME, EncryptedNodeOpenHelper.KEY_CONTENT }, new int[] {
						R.id.topicName, R.id.topicContent });
		setListAdapter(adapter);
		super.onPause();
	}

	private class DialogEncryptionBtnEvent implements OnClickListener {

		private Dialog encryptionDialog;

		public DialogEncryptionBtnEvent(Dialog encryptionDialog) {
			this.encryptionDialog = encryptionDialog;
		}

		@Override
		public void onClick(View arg0) {
			mCursor.moveToPosition(longSelectPosition);
			int id = mCursor.getInt(0);
			String fileName = mCursor.getString(1);
			String fileContent = mCursor.getString(2);
			String keyData = ((EditText) encryptionDialog.findViewById(R.id.encryptKey)).getText().toString();
			// operationDAO.delete(id);
			Log.e("adam", "encryptedkeyData:" + keyData);
			Log.e("adam", "dialog.onclick");

			try {
				EncryptTool encryptTool = new EncryptTool();

				fileContent = encryptTool.encrypt(keyData, fileContent);
				fileName = fileName + " *encrypted*";
				operationDAO.update(id, fileName, fileContent);
				Toast.makeText(EncryptedNoteActivity.this, "encrypted successfully ", Toast.LENGTH_SHORT).show();
			} catch (InvalidKeyException e) {
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (NoSuchPaddingException e) {
				e.printStackTrace();
			} catch (InvalidKeySpecException e) {
				e.printStackTrace();
			} catch (IllegalBlockSizeException e) {
				e.printStackTrace();
			} catch (BadPaddingException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			// encryptTool.encrypt(keyData, str);
			mCursor = operationDAO.query();
			// mCursor.requery();
			startManagingCursor(mCursor);
			ListAdapter adapter = new SimpleCursorAdapter(EncryptedNoteActivity.this,
			// android.R.layout.two_line_list_item,
					R.layout.note_list_component, mCursor,
					// new String[] {People.NAME},
					new String[] { EncryptedNodeOpenHelper.KEY_NAME, EncryptedNodeOpenHelper.KEY_CONTENT }, new int[] {
							R.id.topicName, R.id.topicContent });
			setListAdapter(adapter);
			encryptionDialog.dismiss();
		}
	}

	private class DialogDismiss implements OnClickListener {
		private Dialog dialog;

		public DialogDismiss(Dialog dialog) {
			this.dialog = dialog;
		}

		@Override
		public void onClick(View v) {
			this.dialog.dismiss();
		}

	}

	private class DialogDecryptionBtnEvent implements OnClickListener {
		private Dialog dncryptionDialog;

		public DialogDecryptionBtnEvent(Dialog dncryptionDialog) {
			this.dncryptionDialog = dncryptionDialog;
		}

		@Override
		public void onClick(View v) {
			mCursor.moveToPosition(longSelectPosition);
			int id = mCursor.getInt(0);
			String fileName = mCursor.getString(1);
			Log.e("adam", "fileName:" + fileName + fileName.contains(" *encrypted*"));
			if (!fileName.contains(" *encrypted*")) {
				Log.e("adam", "not Contains encrypted");
				AlertDialog.Builder builder = new AlertDialog.Builder(EncryptedNoteActivity.this);
				builder.setMessage("This note is not encrypted!").setCancelable(false).setNegativeButton("Comfirm",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
				AlertDialog alert = builder.create();
				alert.show();
				return;
			}
			String fileContent = mCursor.getString(2);
			String keyData = ((EditText) dncryptionDialog.findViewById(R.id.encryptKey)).getText().toString();
			// operationDAO.delete(id);
			Log.e("adam", "decryptedkeyData:" + keyData);
			Log.e("adam", "dialog.onclick");

			try {
				EncryptTool encryptTool = new EncryptTool();

				fileContent = encryptTool.decrypt(keyData, fileContent);
				fileName = fileName.replace(" *encrypted*", "");
				operationDAO.update(id, fileName, fileContent);
				Toast.makeText(EncryptedNoteActivity.this, "decrypted successfully ", Toast.LENGTH_SHORT).show();
			} catch (InvalidKeyException e) {
				Toast.makeText(EncryptedNoteActivity.this, "InvalidKeyException", Toast.LENGTH_SHORT).show();
				// e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				Toast.makeText(EncryptedNoteActivity.this, "NoSuchAlgorithmException", Toast.LENGTH_SHORT).show();
				// e.printStackTrace();
			} catch (NoSuchPaddingException e) {
				Toast.makeText(EncryptedNoteActivity.this, "NoSuchPaddingException", Toast.LENGTH_SHORT).show();
				// e.printStackTrace();
			} catch (IllegalBlockSizeException e) {
				Toast.makeText(EncryptedNoteActivity.this, "IllegalBlockSizeException", Toast.LENGTH_SHORT).show();
				// e.printStackTrace();
			} catch (BadPaddingException e) {
				AlertDialog.Builder builder = new AlertDialog.Builder(EncryptedNoteActivity.this);
				builder.setMessage("The Password is not correct!").setCancelable(false).setNegativeButton("Comfirm",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
				AlertDialog alert = builder.create();
				alert.show();
				// e.printStackTrace();
			} catch (InvalidKeySpecException e) {
				Toast.makeText(EncryptedNoteActivity.this, "InvalidKeySpecException", Toast.LENGTH_SHORT).show();
				// e.printStackTrace();
			} catch (IOException e) {
				Toast.makeText(EncryptedNoteActivity.this, "IOException", Toast.LENGTH_SHORT).show();
				// e.printStackTrace();
			}

			// encryptTool.encrypt(keyData, str);
			mCursor = operationDAO.query();
			// mCursor.requery();
			startManagingCursor(mCursor);
			ListAdapter adapter = new SimpleCursorAdapter(EncryptedNoteActivity.this,
			// android.R.layout.two_line_list_item,
					R.layout.note_list_component, mCursor,
					// new String[] {People.NAME},
					new String[] { EncryptedNodeOpenHelper.KEY_NAME, EncryptedNodeOpenHelper.KEY_CONTENT }, new int[] {
							R.id.topicName, R.id.topicContent });
			setListAdapter(adapter);
			dncryptionDialog.dismiss();
		}
	}

	@Override
	protected void onDestroy() {
		operationDAO.close();
		super.onDestroy();
	}

}